package com.stephenone.zhdaily.comment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.stephenone.zhdaily.Constants;
import com.stephenone.zhdaily.R;
import com.stephenone.zhdaily.comment.adapter.CommentCategoryViewBinder;
import com.stephenone.zhdaily.comment.adapter.CommentViewBinder;
import com.stephenone.zhdaily.comment.adapter.EmptyCommentViewBinder;
import com.stephenone.zhdaily.data.bean.Category;
import com.stephenone.zhdaily.data.bean.Comment;
import com.stephenone.zhdaily.data.bean.Comments;
import com.stephenone.zhdaily.data.bean.EmptyComment;
import com.stephenone.zhdaily.data.bean.Footer;
import com.stephenone.zhdaily.homepage.adapter.FooterViewBinder;
import com.stephenone.zhdaily.uitl.RecyclerViewLoadMoreListener;
import com.stephenone.zhdaily.uitl.StatusBarCompat;

import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

public class CommentFragment extends Fragment implements CommentContract.View , CommentCategoryViewBinder.ShortCommentCategoryClickListener{
    private static final String TAG = CommentFragment.class.getSimpleName();
    private long mStroyId;
    private MultiTypeAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private CommentContract.Presenter mPresenter;
    private Items mItems;
    private LinearLayoutManager mManager;
    private boolean isShortCommentsInited = false;
    private boolean isFinalComment = false;
    private long mFinalCommentId;

    public CommentFragment() {
    }

    public static CommentFragment newInstance(long id) {
        CommentFragment fragment = new CommentFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.KEY_STORY_ID,id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mStroyId = getArguments().getLong(Constants.KEY_STORY_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_comment, container, false);
        mRecyclerView = contentView.findViewById(R.id.recyclerView);
        mRecyclerView.addOnScrollListener(new RecyclerViewLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (isShortCommentsInited && !isFinalComment) {
                    mPresenter.loadMore(mFinalCommentId);
                }
            }
        });



        // TODO: 2018/1/31 黏性 滑动  TODO
//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                int visibleItemCount = linearLayoutManager.getChildCount();
//                int totalItemCount = linearLayoutManager.getItemCount();
//                int pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();
//                if ((visibleItemCount + pastVisiblesItems) == totalItemCount  ) { //&& !isloading
////                    mPresenter.loadMore(mCurrentDate);
//                }
//            }
//        });
        mManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mManager);

        mAdapter = new MultiTypeAdapter();
        mAdapter.register(Comment.class, new CommentViewBinder(getActivity()));
        mAdapter.register(Category.class,new CommentCategoryViewBinder(this));
        mAdapter.register(EmptyComment.class,new EmptyCommentViewBinder(getEmptyItemHeight(),getScreenWidth()));
        mAdapter.register(Footer.class,new FooterViewBinder());
        mRecyclerView.setAdapter(mAdapter);
        return contentView;
    }

    private int getEmptyItemHeight() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        Log.e(TAG, "onCreateView: " + dm.heightPixels);
        int screenHeight = dm.heightPixels;

        int actionBarHeight = 0;
        // Calculate ActionBar height
        TypedValue tv = new TypedValue();
        if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
        {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
        }


        int statusBarHeight = StatusBarCompat.getStatusBarHeight(getActivity());

        int titleItemHeight = getActivity().getResources().getDimensionPixelOffset(R.dimen.category_title_height);
        return screenHeight - actionBarHeight- statusBarHeight - titleItemHeight * 2;

    }

    private int getScreenWidth(){
        return getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    public void setPresenter(CommentContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: " );
        mPresenter.subscribe();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }

    @Override
    public void showLongComment(Comments comments) {
        mItems = new Items();
        // TODO: 2018/1/31 评论数量请求
        mItems.add(new Category(true,0));
        if (comments.getComments().size() == 0) {
            mItems.add(new EmptyComment());
        }
        mItems.addAll(comments.getComments());
        mItems.add(new Category(false,0));
        mAdapter.setItems(mItems);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showShortComment(Comments comments) {
        List<Comment> commentList = comments.getComments();
        mItems.addAll(commentList);
        if (commentList.size() >= 20) {
            mItems.add(new Footer());
        }
        mFinalCommentId = commentList.get(commentList.size()- 1).getId();
        mAdapter.notifyDataSetChanged();
        isShortCommentsInited = true;
//        mRecyclerView.smoothScrollToPosition(mItems.size() - comments.getComments().size() + 1);


        RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(getActivity()){
            @Override
            protected int getVerticalSnapPreference() {
                return LinearSmoothScroller.SNAP_TO_START;
            }
        };

        smoothScroller.setTargetPosition(mItems.size() - comments.getComments().size() - 1);

        mManager.startSmoothScroll(smoothScroller);
    }

    @Override
    public void showMoreComment(Comments comments) {
        mItems.remove(mItems.size() - 1);
        List<Comment> commentList = comments.getComments();
        if (commentList.size() == 0) {
            isFinalComment = true;
            mAdapter.notifyDataSetChanged();
            return ;
        }
        mItems.addAll(commentList);
        if (commentList.size() >= 20) {
            mItems.add(new Footer());
        }
        mFinalCommentId = commentList.get(commentList.size()- 1).getId();
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public void onShortCommentCategoryClick() {
        if (!isShortCommentsInited) {
            mPresenter.initShortComment();
        }
    }

}
